package com.mycompany.app.user.dao;

import java.util.List;

import com.mycompany.app.model.User;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
 
/**
 *
 * User DAO
 *
 * @author onlinetechvision.com
 * @since 25 Mar 2012
 * @version 1.0.0
 *
 */

@Transactional
@Repository
public class UserDAO  implements IUserDAO {
	 protected final Log logger = LogFactory.getLog(getClass());
	 
	 @Autowired(required=true)
    private SessionFactory sessionFactory;
 
    /**
     * Get Hibernate Session Factory
     *
     * @return SessionFactory - Hibernate Session Factory
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    /**
     * Set Hibernate Session Factory
     *
     * @param SessionFactory - Hibernate Session Factory
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * Add User
     *
     * @param  User user
     */
  
    public void addUser(User user) {
        getSessionFactory().getCurrentSession().save(user);
    }
 
    /**
     * Delete User
     *
     * @param  User user
     */

    public void deleteUser(User user) {
        getSessionFactory().getCurrentSession().delete(user);
    }
 
    /**
     * Update User
     *
     * @param  User user
     */

    public void updateUser(User user) {
        getSessionFactory().getCurrentSession().update(user);
    }
 
    /**
     * Get User
     *
     * @param  int User Id
     * @return User
     */

    public User getUserById(int id) {
        List list = getSessionFactory().getCurrentSession()
                                            .createQuery("from User where id=?")
                                            .setParameter(0, id).list();
        return (User)list.get(0);
    }
 
    /**
     * Get User List
     *
     * @return List - User list
     */
    public List<User> getUsers() {
        List list = getSessionFactory().getCurrentSession().createQuery("from User").list();
        return list;
    }

	public User getUserByUserName(String username) {
		 logger.info("search userDao :"+username );
		 List list=null;
		 try{
			list = getSessionFactory().getCurrentSession()
	                 .createQuery("from User where username=?")
	                 .setParameter(0, username).list();
			 logger.info("lisUser" +list);
			 
		 }catch(Exception e){
			 logger.error("No se pudo recuperar :"+username ,e);
		 }
		 if(list==null || list.isEmpty()){
			 return null;
		 }
		 return (User)list.get(0);
	}
 
}